<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading" @selection-change="handleSelectionChange">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" v-if="checkPermission(['purchaseContract:add'])" type="primary"
            @click="handleAddContract">新增</el-button>
          <el-button size="mini" v-if="checkPermission(['purchaseContract:del'])" @click="handleDeleteContract()" type="danger"
            :disabled="multipleSelection.length === 0">删除</el-button>
          <el-button size="mini" v-if="checkPermission(['purchaseContract:close'])" @click="handleCloseContract()"
            type="danger" :disabled="multipleSelection.length === 0">关闭合同</el-button>
          <el-button size="mini" v-if="checkPermission(['purchaseContract:execute'])" @click="handleExecuteContract()"
            type="success" :disabled="multipleSelection.length === 0">执行合同</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" @advancedSearch="advancedSearchEvent" placeholder="请输入合同编号" advanced
            advancedWidth="465">
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                <el-form-item label="供应商名称">
                  <el-input v-model="advancedForm.supplier_name" :minlength="2" :maxlength="20" clearable
                    placeholder="请输入供应商名称"></el-input>
                </el-form-item>
                <el-form-item label="时间">
                  <el-date-picker v-model="advancedForm.Contract_time_range" type="daterange" align="center"
                    :editable="false" unlink-panels :clearable="false" :default-time="['00:00:00', '23:59:59']"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp"
                    :picker-options="{ disabledDate(time) { return time.getTime() - 1 >= new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime() + 86400000 - 1 }, shortcuts: MixinPickerShortcuts }">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sn" label="合同编号">
          <template slot-scope="scope">
            <router-link v-if="checkPermission(['purchaseContract'])" style="color: #409eff;" :to="{ name: 'purchaseContractDetail', params: { id: scope.row.id } }">{{
              scope.row.sn }}</router-link>
            <span v-else>{{ scope.row.sn }}</span>
          </template>
        </el-table-column>
        <el-table-column label="签订日期">
          <template slot-scope="scope">{{ scope.row.sign_time | unixToDate }}</template>
        </el-table-column>
        <el-table-column prop="supplier_name" label="供应商" />
        <el-table-column prop="contract_status" label="状态">
          <template slot-scope="scope">{{ statusFilter(scope.row.contract_status) }}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" v-if="scope.row.allowable.allow_edit && checkPermission(['purchaseContract:edit'])"
              @click="handleEditContract(scope.row)">编辑</el-button>
            <el-button type="primary" v-if="checkPermission(['purchaseContract:download'])" size="mini"
              @click="downloadFile(scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>
  </div>
</template>

<script>
import * as API_Setting from '@/api/setting'
import * as File from '@/utils/files'
import * as API_Purchase from '@/api/purchase'
import { Foundation } from '~/ui-utils'
export default {
  name: 'purchaseContract',
  data() {
    return {
      multipleSelection: [],
      supplierList: [],
      deptList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10
      },
      // 高级搜索数据
      advancedForm: {},
      // 列表数据
      tableData: '',
      ContractForm: {}
    }
  },
  mounted() {
    this.GET_ContractList()
    this.GET_DeptList()
  },
  watch: {
    $route: function({ query }) {
      this.params.page_no = 1
      this.GET_ContractList()
    }
  },
  methods: {
    statusFilter(val) {
      switch (val) {
        case 'NEW':
          return '未执行'
        case 'EXECUTING':
          return '执行中'
        case 'CLOSED':
          return '已关闭'
        default:
          return ''
      }
    },
    handleExecuteContract() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
      this.$confirm('确定要执行这些采购合同吗？', '提示', { type: 'warning' }).then(() => {
        const ids = this.multipleSelection.map(item => item.id)
        API_Purchase.executeContract(ids).then(() => {
          this.$message.success('执行成功！')
          this.GET_ContractList()
        })
      }).catch(() => { })
    },
    handleCloseContract() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
      this.$confirm('确定要关闭这些采购合同吗？', '提示', { type: 'warning' }).then(() => {
        const ids = this.multipleSelection.map(item => item.id)
        API_Purchase.closeContract(ids).then(() => {
          this.$message.success('关闭成功！')
          this.GET_ContractList()
        })
      }).catch(() => { })
    },
    downloadFile(row) {
      const templateConfig = {
        name: '合同管理' + row.id,
        url: row.contract_annex
      }
      File.downloadFile(templateConfig)
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    /** 添加采购计划 */
    handleEditContract(row) {
      this.$router.push({
        name: 'purchaseContractEdit',
        params: { id: row.id }
      })
    },
    handleDeleteContract() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
      this.$confirm('确定要删除这些采购合同吗？', '提示', { type: 'warning' }).then(() => {
        const ids = this.multipleSelection.map(item => item.id)
        API_Purchase.deleteContract(ids).then(() => {
          this.$message.success('删除成功！')
          this.GET_ContractList()
        })
      }).catch(() => { })
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_ContractList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_ContractList()
    },

    /** 添加采购计划 */
    handleAddContract() {
      this.$router.push({
        name: 'purchaseContractAdd',
        params: { callback: this.GET_ContractList }
      })
    },
    /** 打印采购计划 */
    handlePrintContractDialog(row) {
      this.GET_ContractDetail(row.id)
    },
    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        sn: data
      }
      Object.keys(this.advancedForm).forEach((key) => delete this.params[key])
      this.params.page_no = 1
      this.GET_ContractList()
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      delete this.params.start_time
      delete this.params.end_time
      if (this.advancedForm.Contract_time_range) {
        this.params.start_time = parseInt(Number(this.advancedForm.Contract_time_range[0]) / 1000)
        this.params.end_time = parseInt(Number(this.advancedForm.Contract_time_range[1]) / 1000)
      }
      delete this.params.Contract_time_range
      this.params.page_no = 1
      this.GET_ContractList()
    },
    /** 获取采购计划列表 */
    GET_ContractList() {
      API_Purchase.getContractList(this.params).then(response => {
        this.tableData = response
      })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.print {
  margin-left: 790px;
}

.tips-t {
  display: flex;
  padding: 10px 0;

  div {
    flex: 1;
    text-align: center;
  }
}

.tips-f {
  padding: 20px 0;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
